#include "debugtool.h"

#ifdef DEBUG_OPEN_CONSOLE

void SAFE_OPEN_CONSOLE_INIT()
{
	AllocConsole();  
	HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
	int hCrt = _open_osfhandle((long)handle, _O_TEXT);
	FILE * hf = _fdopen(hCrt,"w");  
	*stdout = *hf;
}

void SAFE_OPEN_CONSOLE_FINALIZE()
{
	FreeConsole();
}

void SAFE_SETCONSOLETITLE_FINALIZE(char* title)
{	
	SetConsoleTitleA(title);
}

#endif //DEBUG_OPEN_CONSOLE

#ifdef DEBUG_NEW_DELETE

LogMsgInfoList	g_logMsgInfoList;

void AppendLogMsg(void* ptr, size_t size, const char* file, const int line)
{
	LogMsgInfo log;
	log.ptr = ptr;
	log.size = size;
	strcpy(log.file, file);
	log.line = line;

	g_logMsgInfoList.push_back(log);
}

void RemoveLogMsg(void* ptr)
{	
	if(g_logMsgInfoList.empty())
		return;

	LogMsgInfoList::iterator itList = g_logMsgInfoList.begin();
	while(itList != g_logMsgInfoList.end())
	{
		LogMsgInfo pLog = *itList;
		if(pLog.ptr == ptr)
		{
			g_logMsgInfoList.erase(itList);
			break;
		}
		itList++;
	}
}

void* operator new(size_t size, const char* file, const int line)
{
	void* ptr = ::operator new(size);

	AppendLogMsg(ptr, size, file, line);

	return ptr;
}

void operator delete(void* ptr, const char* file, const int line)
{
	if(ptr != NULL)
	{
		RemoveLogMsg(ptr);
		free(ptr);
	}
}

void operator delete(void* ptr)
{
	if(ptr != NULL)
	{
		RemoveLogMsg(ptr);
		free(ptr);
	}
}

#endif //DEBUG_NEW_DELETE